﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XLang
{
    /// <summary>
    /// 关键字规则
    /// </summary>
    public class KeywordRule
    {
        public string Keyword { get; set; }

        public List<string> State { get; set; }

        public Type Type { get; set; }

        public Func<Keyword> Create { get; set; }
        public KeywordRule(Type type)
        {
            var keywordAttributes = type.GetCustomAttributes(typeof(KeywordAttribute), false);
            if (keywordAttributes.Length != 1) throw new Exception("Keyword must have one KeywordAttribute.");

            var keywordAttribute = (KeywordAttribute)keywordAttributes[0];
            this.Keyword = keywordAttribute.Value;

            var stateAttributes = type.GetCustomAttributes(typeof(StateAttribute), false);
            this.State = new List<string>();
            if (stateAttributes.Length == 0)
            {
                this.State.Add("Initial");
            }
            else
            {
                foreach (var stateObj in stateAttributes)
                {
                    var state = (StateAttribute)stateObj;
                    this.State.Add(state.Value);
                }
            }

            this.Type = type;

            this.Create = () =>
            {
                var obj = Activator.CreateInstance(Type);
                return obj as Keyword;
            };
        }
    }
}
